//package cn.aitrox.ry.app.web.interceptor;
//
//import cn.aitrox.ry.bean.RespResult;
//import cn.aitrox.ry.common.exception.CustomBizException;
//import cn.aitrox.ry.common.interceptor.UserThreadLocal;
//import cn.aitrox.ry.constant.CommonConstant;
//import cn.aitrox.ry.enumtype.RespCodeEnum;
//import cn.aitrox.ry.service.auth.dto.resource.out.AuthResourceDetailDto;
//import cn.aitrox.ry.service.auth.dto.user.resource.out.AuthUserResourceListOutDto;
//import cn.aitrox.ry.service.auth.feign.AuthResourceFeign;
//import cn.aitrox.ry.service.auth.feign.AuthUserResourceFeign;
//import cn.aitrox.ry.service.cache.dto.in.CacheGetAndExpireInDto;
//import cn.aitrox.ry.service.cache.dto.in.CacheSetInDto;
//import cn.aitrox.ry.service.cache.enumtype.CacheBizEnum;
//import cn.aitrox.ry.service.cache.feign.CacheFeign;
//import cn.aitrox.ry.util.ArrayUtil;
//import cn.aitrox.ry.util.JSONUtil;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Lazy;
//import org.springframework.stereotype.Component;
//import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.util.Arrays;
//import java.util.List;
//import java.util.regex.Matcher;
//import java.util.regex.Pattern;
//import java.util.stream.Collectors;
//
//
//@Component
//public class AuthInterceptor extends HandlerInterceptorAdapter {
//
//    @Autowired
//    @Lazy
//    private AuthResourceFeign authResourceFeign;
//
//    @Autowired
//    @Lazy
//    private AuthUserResourceFeign authUserResourceFeign;
//
//    @Autowired
//    private UserThreadLocal userThreadLocal;
//
//    @Autowired
//    @Lazy
//    private CacheFeign cacheFeign;
//
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//
//        String requestURI = request.getRequestURI();
//        String method = request.getMethod();
//
//        RespResult<String> respResult = cacheFeign.getAndExpire(new CacheGetAndExpireInDto(CacheBizEnum.APP_WEB, "NEED_AUTH_RESOURCE_LIST", 1800));
//        if (!respResult._isOk()) {
//            throw new CustomBizException(RespCodeEnum.SYSTEM_ERROR.getCode(), "查询缓存失败");
//        }
//
//        List<AuthResourceDetailDto> needAuthResources;
//        if (StringUtils.isNotEmpty(respResult.getData())) {
//            needAuthResources = JSONUtil.parseArray(respResult.getData(), AuthResourceDetailDto.class);
//        } else {
//            // 查询所有需要进行鉴权的api
//            List<AuthResourceDetailDto> allResourceDto = authResourceFeign.all();
//            needAuthResources = allResourceDto.stream().filter(x -> StringUtils.isNotEmpty(x.getApiUri())).collect(Collectors.toList());
//
//            // 缓存
//            cacheFeign.set(new CacheSetInDto(CacheBizEnum.APP_WEB, "NEED_AUTH_RESOURCE_LIST", JSONUtil.toJson(needAuthResources), 1800));
//        }
//
//        // 如果没有直接放行
//        if (!ArrayUtil.isEmpty(needAuthResources)) {
//            return true;
//        }
//
//        respResult = cacheFeign.getAndExpire(new CacheGetAndExpireInDto(CacheBizEnum.APP_WEB, "USER_RESOURCES_" + userThreadLocal.getUser().getId(), 1800));
//        if (!respResult._isOk()) {
//            throw new CustomBizException(RespCodeEnum.SYSTEM_ERROR.getCode(), "查询缓存失败");
//        }
//
//        List<AuthResourceDetailDto> resourceList;
//        if (StringUtils.isNotEmpty(respResult.getData())) {
//            resourceList = JSONUtil.parseArray(respResult.getData(), AuthResourceDetailDto.class);
//        } else {
//            // 查询用户权限资源
//            RespResult<AuthUserResourceListOutDto> resourceResp = authUserResourceFeign.list(userThreadLocal.getUser().getId());
//            if (!resourceResp._isOk()) {
//                throw new CustomBizException(RespCodeEnum.SYSTEM_ERROR, "查询用户权限失败");
//            }
//            resourceList = resourceResp.getData().getResourceList();
//        }
//
//        // 找出与请求的uri与method匹配的resource
//        AuthResourceDetailDto resourceMatcher = needAuthResources.stream().filter(x -> {
//            String regex = x.getApiMethod();
//            Pattern pattern = Pattern.compile(regex);
//            Matcher matcher = pattern.matcher(requestURI);
//            String[] methods = x.getApiMethod().split(CommonConstant.DEFAULT_SEPARATOR);
//            return matcher.find() && Arrays.stream(methods).filter(y -> y.equalsIgnoreCase(method)).count() > 0;
//
//        }).findFirst().orElse(null);
//
//        // 如果没有匹配到说明访问的资源不在控制范围，放行
//        if (null == resourceMatcher) {
//            return true;
//        }
//
//        if (ArrayUtil.isEmpty(resourceList)) {
//            // 用户没有任何资源权限
//            throw new CustomBizException(RespCodeEnum.NO_PERMISSION);
//        }
//
//        // 查询用户是否有这个资源的访问权限
//        AuthResourceDetailDto mathcherResource = resourceList.stream().filter(x -> x.getId().equals(resourceMatcher.getId())).findFirst().orElse(null);
//        if (null == mathcherResource) {
//            throw new CustomBizException(RespCodeEnum.NO_PERMISSION);
//        }
//        return true;
//    }
//}
